import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:hxdj/common/base_page/base_page.dart';
import 'package:hxdj/common/components/my_alert.dart';
import 'package:hxdj/common/dio/dio_http.dart';
import 'package:hxdj/common/my_pay_manager.dart';
import 'package:hxdj/home/home_viewmodel.dart';
import 'dart:convert';

import 'package:hxdj/mine/pay/select_pay.dart';
import 'package:provider/provider.dart';

class MemberCenterViewModel extends BaseViewModel {
  late MemberDetailModel? memberDetailModel;

  late int index = 2;

  late VipPriceList? vipPriceModel;

  late bool isServiceAgreement = false;
  @override
  requestData({Function(dynamic)? onSuccess, Function(dynamic)? onError}) async {
    setState(ViewState.loading);
    // 去请求服务器数据.
    Map<String, dynamic> resultMap = await DioHttpManager().request(MyApi.vipLevelList, method: DioHttpManager.post);
    memberDetailModel = MemberDetailModel.fromMap(resultMap);
    final List<VipPriceList>? vipPriceList = memberDetailModel?.detailData?.svip?.vipPriceList;
    if (vipPriceList?.isNotEmpty == true) {
      vipPriceModel = vipPriceList?[index];
    }
    // 更新页面.
    setState(ViewState.normal);
  }

  //选择Vip的TC
  selectVip(int x) {
    index = x;
    vipPriceModel = memberDetailModel?.detailData?.svip?.vipPriceList?[x];
    notifyListeners();
  }

  //确认服务协议
  confirmServiceAgreement() {
    isServiceAgreement = !isServiceAgreement;
    notifyListeners();
  }

  //开通Vip
  openVip() async {
    String channelPay = "";
    // //选择了那个支付方式, 传一个闭包过去
    Future<void> onSelectCallback(String value) async {
      if (value == "ic_wechat_pay") {
        //微信支付
        channelPay = "wechaapp";
      } else if (value == "ic_ali_pay") {
        //支付宝支付
        channelPay = "aliapppay";
      } else {
        //其他支付方式
        debugPrint("object $value");
      }
      startPay(channelPay);
    }

    //查看 当前支付的支持那种方式
    Map<String, dynamic> paramsObjectMap = {
      "price": vipPriceModel?.vipPriceIos ?? "0",
      "onSelectCallback": onSelectCallback
    };
    MyAlertManager.sheetAlert(AlertType.customWidget, context, "", "", child: SelectPayPage(object: paramsObjectMap));
  }

  startPay(String channelPay) async {
    // //选择支付方式
    Map<String, dynamic> resultMap = await DioHttpManager().request(MyApi.payInfo,
        method: DioHttpManager.post,
        data: {"type": "2", "v_id": "0", "order_id": vipPriceModel?.id, "channel_pay": channelPay});

    if (resultMap['code'] == 0) {
      //查看 当前支付的支持那种方式
      Map<String, dynamic> resultPayManagerMap = resultMap["data"];

      String aliPayUrl = resultPayManagerMap['pay_url'];
      String orderId = resultPayManagerMap['order_id'].toString();

      Map<String, dynamic> weixinUrlMap = resultPayManagerMap['weixin_url'];

      //去支付
      switch (channelPay) {
        case "aliapppay":
          {
            goAliPay(aliPayUrl, orderId, context);
          }

          break;
        case "wechaapp":
          {
            MyPayManager().goWechatPay(weixinUrlMap, (p0) {});
          }

          break;
        default:
      }
    } else {
      EasyLoading.showToast(resultMap["msg"]);
    }
  }

  goAliPay(String aliPayUrl, String orderId, BuildContext context) {
    MyPayManager().goAliPay(aliPayUrl).then((value) {
      debugPrint("value: $value");
      switch (value["payReuslt"]) {
        case "success":
          MyAlertManager.sheetAlert(AlertType.sheetPayStatue, context, "支付完成", "ic_pay_success",
              object: {"buttonTitle": "我知道了"}, onSure: () {
            Navigator.of(context).popUntil((route) => route.isFirst);
            //刷新, 首页, 我的页面
            HomeViewModel homeViewModel = Provider.of<HomeViewModel>(context, listen: false);
            homeViewModel.requestMemberInfo();
            homeViewModel.reloadOrderData();
          });
          break;
        default:
          MyAlertManager.sheetAlert(AlertType.sheetPayStatue, context, "支付失败", "ic_pay_fail",
              object: {"buttonTitle": "重新支付"}, onSure: () {
            goAliPay(aliPayUrl, orderId, context);
          });
          break;
      }
    });
  }
}

class MemberDetailModel {
  final DetailData? detailData;
  final MemberInfo? memberInfo;

  MemberDetailModel({
    this.detailData,
    this.memberInfo,
  });

  factory MemberDetailModel.fromJson(String str) => MemberDetailModel.fromMap(json.decode(str));

  String toJson() => json.encode(toMap());

  factory MemberDetailModel.fromMap(Map<String, dynamic> json) => MemberDetailModel(
        detailData: json["data"] == null ? null : DetailData.fromMap(json["data"]),
        memberInfo: json["member_info"] == null ? null : MemberInfo.fromMap(json["member_info"]),
      );

  Map<String, dynamic> toMap() => {
        "detailData": detailData?.toMap(),
        "member_info": memberInfo?.toMap(),
      };
}

class DetailData {
  final Svip? svip;

  DetailData({
    this.svip,
  });

  factory DetailData.fromJson(String str) => DetailData.fromMap(json.decode(str));

  String toJson() => json.encode(toMap());

  factory DetailData.fromMap(Map<String, dynamic> json) => DetailData(
        svip: json["SVIP"] == null ? null : Svip.fromMap(json["SVIP"]),
      );

  Map<String, dynamic> toMap() => {
        "SVIP": svip?.toMap(),
      };
}

class Svip {
  final int? id;
  final String? title;
  final String? aliasTitle;
  final String? chatContent;
  final int? isDefalut;
  final List<VipPriceList>? vipPriceList;
  final String? vipPrivilegesTitle;
  final List<VipPrivilegesList>? vipPrivilegesList;

  Svip({
    this.id,
    this.title,
    this.aliasTitle,
    this.chatContent,
    this.isDefalut,
    this.vipPriceList,
    this.vipPrivilegesTitle,
    this.vipPrivilegesList,
  });

  factory Svip.fromJson(String str) => Svip.fromMap(json.decode(str));

  String toJson() => json.encode(toMap());

  factory Svip.fromMap(Map<String, dynamic> json) => Svip(
        id: json["id"],
        title: json["title"],
        aliasTitle: json["alias_title"],
        chatContent: json["chat_content"],
        isDefalut: json["is_defalut"],
        vipPriceList: json["vip_price_list"] == null
            ? []
            : List<VipPriceList>.from(json["vip_price_list"]!.map((x) => VipPriceList.fromMap(x))),
        vipPrivilegesTitle: json["vip_privileges_title"],
        vipPrivilegesList: json["vip_privileges_list"] == null
            ? []
            : List<VipPrivilegesList>.from(json["vip_privileges_list"]!.map((x) => VipPrivilegesList.fromMap(x))),
      );

  Map<String, dynamic> toMap() => {
        "id": id,
        "title": title,
        "alias_title": aliasTitle,
        "chat_content": chatContent,
        "is_defalut": isDefalut,
        "vip_price_list": vipPriceList == null ? [] : List<dynamic>.from(vipPriceList!.map((x) => x.toMap())),
        "vip_privileges_title": vipPrivilegesTitle,
        "vip_privileges_list":
            vipPrivilegesList == null ? [] : List<dynamic>.from(vipPrivilegesList!.map((x) => x.toMap())),
      };
}

class VipPriceList {
  final int? id;
  final String? vipName;
  final String? vipPrice;
  final String? vipPriceIos;
  final String? iosProductId;
  final int? vipOverTime;
  final String? vipImgUrl;
  final int? vipChatNum;
  final String? discounts;
  final String? vipTitle;
  final String? discountsRatioStr;
  final String? discountsStr;
  final String? popupVipName;
  final String? popupVipTitle;
  final int? isUse;

  VipPriceList({
    this.id,
    this.vipName,
    this.vipPrice,
    this.vipPriceIos,
    this.iosProductId,
    this.vipOverTime,
    this.vipImgUrl,
    this.vipChatNum,
    this.discounts,
    this.vipTitle,
    this.discountsRatioStr,
    this.discountsStr,
    this.popupVipName,
    this.popupVipTitle,
    this.isUse,
  });

  factory VipPriceList.fromJson(String str) => VipPriceList.fromMap(json.decode(str));

  String toJson() => json.encode(toMap());

  factory VipPriceList.fromMap(Map<String, dynamic> json) => VipPriceList(
        id: json["id"],
        vipName: json["vip_name"],
        vipPrice: json["vip_price"],
        vipPriceIos: json["vip_price_ios"],
        iosProductId: json["ios_product_id"],
        vipOverTime: json["vip_over_time"],
        vipImgUrl: json["vip_img_url"],
        vipChatNum: json["vip_chat_num"],
        discounts: json["discounts"],
        vipTitle: json["vip_title"],
        discountsRatioStr: json["discounts_ratio_str"],
        discountsStr: json["discounts_str"],
        popupVipName: json["popup_vip_name"],
        popupVipTitle: json["popup_vip_title"],
        isUse: json["is_use"],
      );

  Map<String, dynamic> toMap() => {
        "id": id,
        "vip_name": vipName,
        "vip_price": vipPrice,
        "vip_price_ios": vipPriceIos,
        "ios_product_id": iosProductId,
        "vip_over_time": vipOverTime,
        "vip_img_url": vipImgUrl,
        "vip_chat_num": vipChatNum,
        "discounts": discounts,
        "vip_title": vipTitle,
        "discounts_ratio_str": discountsRatioStr,
        "discounts_str": discountsStr,
        "popup_vip_name": popupVipName,
        "popup_vip_title": popupVipTitle,
        "is_use": isUse,
      };
}

class VipPrivilegesList {
  final int? id;
  final String? img;
  final String? name;
  final String? desc;
  final int? isOpen;

  VipPrivilegesList({
    this.id,
    this.img,
    this.name,
    this.desc,
    this.isOpen,
  });

  factory VipPrivilegesList.fromJson(String str) => VipPrivilegesList.fromMap(json.decode(str));

  String toJson() => json.encode(toMap());

  factory VipPrivilegesList.fromMap(Map<String, dynamic> json) => VipPrivilegesList(
        id: json["id"],
        img: json["img"],
        name: json["name"],
        desc: json["desc"],
        isOpen: json["is_open"],
      );

  Map<String, dynamic> toMap() => {
        "id": id,
        "img": img,
        "name": name,
        "desc": desc,
        "is_open": isOpen,
      };
}

class MemberInfo {
  final String? nickname;
  final String? memberImg;
  final int? footmarkShow;
  final int? isVip;
  final String? vipEndTime;
  final int? vipType;
  final String? levelName;
  final String? vipTitle;
  final String? vipDesc;

  MemberInfo({
    this.nickname,
    this.memberImg,
    this.footmarkShow,
    this.isVip,
    this.vipEndTime,
    this.vipType,
    this.levelName,
    this.vipTitle,
    this.vipDesc,
  });

  factory MemberInfo.fromJson(String str) => MemberInfo.fromMap(json.decode(str));

  String toJson() => json.encode(toMap());

  factory MemberInfo.fromMap(Map<String, dynamic> json) => MemberInfo(
        nickname: json["nickname"],
        memberImg: json["member_img"],
        footmarkShow: json["footmark_show"],
        isVip: json["is_vip"],
        vipEndTime: json["vip_end_time"],
        vipType: json["vip_type"],
        levelName: json["level_name"],
        vipTitle: json["vip_title"],
        vipDesc: json["vip_desc"],
      );

  Map<String, dynamic> toMap() => {
        "nickname": nickname,
        "member_img": memberImg,
        "footmark_show": footmarkShow,
        "is_vip": isVip,
        "vip_end_time": vipEndTime,
        "vip_type": vipType,
        "level_name": levelName,
        "vip_title": vipTitle,
        "vip_desc": vipDesc,
      };
}
